package com.example.lenovo.asia5b.commodity.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.lenovo.asia5b.commodity.bean.AllEvaluateBean;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import fay.frame.fast.F;
import fay.frame.ui.U;
import com.example.lenovo.asia5b.ui.CircleImageView;
import com.example.lenovo.asia5b.ui.DownloadPicture;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.ui.photoview.ImagePagerActivity;
import com.example.lenovo.asia5b.util.DensityUtil;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;

import static com.wushi.lenovo.asia5b.R.id.ll_imag;
import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;

/**
 * Created by lenovo on 2017/7/1.
 */

public class AllEvaluateAdapter extends BaseAdapter implements ICallBack

{

    private LayoutInflater mInflater;
    private int cur_pos = 0;// 当前显示的一行
    private Context context;
    private F F;
    private List<AllEvaluateBean> lists ;
    private LoadingDalog loadingDalog;
    private int positionHome;
    private String typeHome;


    public AllEvaluateAdapter(Context context) {
        this.context = context;
        this.mInflater = LayoutInflater.from(context);
        F = new F(context);
//        urls_3.add("https://asia5b.com/data/category/12_20161229popwci.jpg");
//        urls_3.add("https://asia5b.com/data/category/175_20161227pwcazf.jpg");
//        urls_3.add("https://asia5b.com/data/category/176_20161227nibtaf.jpg");
//        urls_3.add("https://asia5b.com/data/category/6_20161227wfpsdc.jpg");
//        urls_3.add("https://asia5b.com/data/category/177_20161227uetzqv.jpg");
        lists = new ArrayList<AllEvaluateBean>();
        loadingDalog = new LoadingDalog(context);
    }

    @Override
    public int getCount() {
        return lists.size();
    }

    @Override
    public Object getItem(int arg0) {
        return lists.get(arg0);
    }

    @Override
    public long getItemId(int arg0) {
        return arg0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.item_all_evaluate, null);
            holder.ll_imag = (LinearLayout)convertView.findViewById(ll_imag);
            holder.image_head = (CircleImageView)convertView.findViewById(R.id.image_head);
            holder.txt_name=(TextView)convertView.findViewById(R.id.txt_name);
            holder.txt_goods_attr=(TextView)convertView.findViewById(R.id.txt_goods_attr);
            holder.txt_content=(TextView)convertView.findViewById(R.id.txt_content);
            holder.txt_value = (TextView)convertView.findViewById(R.id.txt_value);
            holder.txt_cmmt = (TextView)convertView.findViewById(R.id.txt_cmmt);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        AllEvaluateBean bean = lists.get(position);
        holder.ll_imag.removeAllViews();
        //添加图片组
        if (!TextUtils.isEmpty(bean.cmmt_img)) {
            initTitView(holder.ll_imag,bean);
        }
        DownloadPicture.loadHearNetwork(bean.avatar,holder.image_head);
        holder.txt_name.setText(bean.user_name);
        holder.txt_content.setText(bean.content);
        holder.txt_goods_attr.setText(bean.add_time+"\t"+bean.goods_attr);
        int id_value = Integer.parseInt(bean.id_value);
        if (id_value == 0) {
            holder.txt_value.setText(context.getResources().getString(R.string.like));
        } else if (id_value > 999) {
            holder.txt_value.setText("999");
        } else {
            holder.txt_value.setText(bean.id_value);
        }
        String type = "2";
        //先默认全部未点赞
        if (bean.ishave.equals("1")) {
            type = "1";
            Drawable rightDrawable = ContextCompat.getDrawable(context,R.drawable.rate_like_sel_button);
            rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
            holder.txt_value.setCompoundDrawables(rightDrawable, null, null, null);
        } else {
            Drawable rightDrawable = ContextCompat.getDrawable(context,R.drawable.rate_like_button);
            rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
            holder.txt_value.setCompoundDrawables(rightDrawable, null, null, null);
        }
        holder.txt_value.setOnClickListener(new ValueOnClick(position,type));

        int cmmt_nums  = Integer.parseInt(bean.cmmt_nums);
        if (cmmt_nums == 0) {
            holder.txt_cmmt.setText(context.getResources().getString(R.string.comment));
        } else if (cmmt_nums > 999) {
            holder.txt_cmmt.setText("999");
        } else {
            holder.txt_cmmt.setText(bean.cmmt_nums);
        }

        return convertView;
    }

    private class ViewHolder {
        LinearLayout ll_imag;
        CircleImageView image_head;
        TextView txt_name,txt_goods_attr,txt_content,txt_value,txt_cmmt;

    }

    public class  ValueOnClick implements View.OnClickListener {
        int position;
        String type;
        public ValueOnClick(int position,String type)  {
            this.position = position;
            this.type = type;
        }


        @Override
        public void onClick(View v) {
            if (null ==getUserBean()) {
                U.Toast(context,context.getResources().getString(R.string.qdlzh));
                return;
            }
            AllEvaluateBean bean = lists.get(position);
            likeData(bean,type);
            positionHome = position;
            typeHome = type;
        }
    }

    public void likeData(AllEvaluateBean bean,String type) {
        try {
            loadingDalog.show();
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.COMMENT_LIKE;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String user_id = getUserBean().user_id;
            String[] sort = {"comment_id"+bean.comment_id,"type"+type,"user_id"+user_id,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("comment_id", bean.comment_id);
            parmaMap.put("type", type);
            parmaMap.put("user_id",user_id);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        }catch (Exception e) {

        }
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json =  (JSONObject)result;
                        int state = (int)json.getInt("State");
                        if (state == 0) {
                            U.Toast(context,context.getString(R.string.cg));
                            String likenums = json.getString("likenums");
                            lists.get(positionHome).id_value = likenums;
                            if (typeHome.equals("1")) {
                                lists.get(positionHome).ishave = "0";
                            } else {
                                lists.get(positionHome).ishave = "1";
                            }
                            notifyDataSetChanged();
                        }  else if(state == 1){
                            U.Toast(context,context.getResources().getString(R.string.qmsb));
                        }else if(state == 2){
                            U.Toast(context,context.getString(R.string.cscw));
                        }else if(state == 3){
                            U.Toast(context,context.getString(R.string.wdl));
                        }else if(state == 4){
                            U.Toast(context,context.getString(R.string.mysj));
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
            }
        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    public void initTitView(LinearLayout ll_imag, AllEvaluateBean bean ) {
        try {
            JSONArray jsonArray = new JSONArray(bean.cmmt_img);
            final  ArrayList<String> urls2 = new ArrayList<String>();
            int width = DensityUtil.getScreenWidth(context) - 90;
            LinearLayout mLayout = null;
            for (int i = 0; i < jsonArray.length(); i++) {
                if (i % 3 == 0) {
                    mLayout = new LinearLayout(context);
                    mLayout.setLayoutParams(new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT));
                    mLayout.setOrientation(LinearLayout.HORIZONTAL);
                    mLayout.setWeightSum(3);
                    ll_imag.addView(mLayout);
                }
                View hotSaleView = LayoutInflater.from(context).inflate(R.layout.item_hot_sale, null);
                hotSaleView.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
                ImageView image_commodity = (ImageView) hotSaleView.findViewById(R.id.image_commodity);
                TextView txt_name = (TextView) hotSaleView.findViewById(R.id.txt_name);

                image_commodity.setLayoutParams(new LinearLayout.LayoutParams(
                        width / 3,
                        width / 3));
                image_commodity.setTag(i);
                 String cmmt_img = jsonArray.getString(i);
                urls2.add(cmmt_img);
                DownloadPicture.loadNetwork(cmmt_img, image_commodity);
                image_commodity.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        imageBrower((int) view.getTag(), urls2);
                    }
                });
                txt_name.setVisibility(View.GONE);
                mLayout.addView(hotSaleView);
            }
        } catch (Exception e) {

        }
    }


    /**
     * 打开图片查看器
     *
     * @param position
     * @param urls2
     */
    protected void imageBrower(int position, ArrayList<String> urls2) {
        Intent intent = new Intent(context, ImagePagerActivity.class);
        // 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls2);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
        context.startActivity(intent);
    }

    public void setLists(List<AllEvaluateBean> lists) {
        this.lists = lists;
    }

    public List<AllEvaluateBean> getLists() {
        return lists;
    }
}
